//
//  GIFPickerManager.swift
//  GifUsage
//
//  Created by han on 2020/12/17.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import UIKit
import Photos

class GIFPickerManager: NSObject {
    static let shared = GIFPickerManager()
    
    /// 权限：判断是否有权限
    func isAuthorized(completion: ((Bool) -> Void)? = nil) -> Bool? {
        let status = PHPhotoLibrary.authorizationStatus()
        var authorized: Bool? = false
        switch status {
        case .authorized: // 授权
            authorized = true
        case .notDetermined: // 尚未决定
            authorized = nil
            PHPhotoLibrary.requestAuthorization { (state) in
                DispatchQueue.main.async {
                    if state == .authorized || state == .limited {
                        completion?(true)
                    } else {
                        completion?(false)
                    }
                }
            }
        case .denied: // 拒绝
            authorized = false
        case .restricted: // 没有访问权限
            authorized = false
        case .limited: //  iOS 14  允许访问部分相册内容
            authorized = true
        @unknown default:
            break
        }
        return authorized
    }
    
    /// 获取相册列表
    func fetchCollection() -> [AlbumItem] {
        var items:[AlbumItem] = []
        
        // 获取到相簿的所有image/video资源
        func fetchAsset(_ collection: PHFetchResult<PHCollection>) {
            let options = PHFetchOptions()
            options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            //            options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) // image
            
            for i in 0 ..< collection.count {
                // 将文件夹剔除
                guard let collectionItem = collection[i] as? PHAssetCollection else { continue }
                let assetResult = PHAsset.fetchAssets(in: collectionItem, options: options)
                
                // 空相簿不显示
                if assetResult.count > 0 {
                    items.append(AlbumItem(title: collectionItem.localizedTitle, fetchResult: assetResult))
                }
            }
        }
        
        let fetchOptions = PHFetchOptions()
        // 系统的智能相簿
        let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions) as! PHFetchResult<PHCollection>
        
        // 用户创建的相簿/文件夹
        let userOptions = PHFetchOptions()
        let userCollections = PHCollectionList.fetchTopLevelUserCollections(with: userOptions)
        // 用户创建的有可能是相簿有可能是文件夹 PHCollection：PHAssetCollection 和 PHCollectionList
        
        fetchAsset(smartAlbums)
        fetchAsset(userCollections)
        
        return items
    }
    
    /// 按照类型获取
    func fetchAsset(_ collectionType: AssetCollectionType) -> PHFetchResult<PHAsset> {
        
        let fetchOptions = PHFetchOptions()
        // 系统的智能相簿
        let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: collectionType.value, options: fetchOptions)
        
        let options = PHFetchOptions()
        options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        if collectionType == .image {
            options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
        }
        guard let collectionItem = smartAlbums.firstObject  else { return PHFetchResult<PHAsset>() }
        let assetResult = PHAsset.fetchAssets(in: collectionItem, options: options)
        
        return assetResult
    }
    
    func fetchAllAsset() -> PHFetchResult<PHAsset> {
        let allPhotosOptions = PHFetchOptions()
        allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
        return PHAsset.fetchAssets(with: allPhotosOptions)
    }
}

// 相簿列表：[AlbumItem]
// 相簿 对应着PHAssetCollection
struct AlbumItem {
    var title: String?
    
    //相簿内的资源
    var fetchResult: PHFetchResult<PHAsset>
    // PHAsset每个图片/video资源
}

enum FunctionType {
    case imageToGIF
    case gifToImage
    case videoToGIF
    case livePhotoToGIF
    case burstToGIF
    case editGIF
    
    var assetType: AssetCollectionType {
        switch self {
        case .imageToGIF:
            return .image
        case .videoToGIF:
            return .video
        case .livePhotoToGIF:
            return .livePhoto
        case .burstToGIF:
            return .burst
        case .gifToImage:
            return .gif
        case .editGIF:
            return .gif
        }
    }
    
    var title: String {
        switch self {
        case .imageToGIF:
            return "image生成GIF"
        case .videoToGIF:
            return "video转GIF"
        case .livePhotoToGIF:
            return "livePhoto转GIF"
        case .burstToGIF:
            return "连拍转GIF"
        case .gifToImage:
            return "GIF提取Image"
        case .editGIF:
            return "编辑GIF"
        }
    }
}

enum AssetCollectionType {
    case image
    case video
    case livePhoto
    case burst
    case gif
    
    var description: String {
        switch self {
        case .image:
            return "图片"
        case .video:
            return "视频"
        case .livePhoto:
            return "LivePhoto"
        case .burst:
            return "连拍"
        case .gif:
            return "GIF"
        }
    }
    
    var value: PHAssetCollectionSubtype {
        switch self {
        case .image:
            return .smartAlbumUserLibrary
        case .video:
            return .smartAlbumVideos
        case .livePhoto:
            return .smartAlbumLivePhotos
        case .burst:
            return .smartAlbumBursts
        case .gif:
            return .smartAlbumAnimated
        }
    }
}



/*
 PHAssetCollectionType:
 album: 相册, 从 iTunes 同步来的相册，以及用户在 Photos 中自己建立的相册（除了不包括系统相簿，所有自定义的相簿都在包括自定义文件夹下的相簿）
 smartAlbum: 系统的智能相册,经由相机得来的相册
 
 PHAssetCollectionTypeAlbum regular subtypes
 PHAssetCollectionTypeAlbum shared subtypes
 PHAssetCollectionTypeSmartAlbum subtypes
 */

